package com.huanxing.cloud.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.product.api.dto.GoodsSkuStockReqDTO;
import com.huanxing.cloud.product.api.entity.GoodsSku;
import com.huanxing.cloud.product.mapper.GoodsSkuMapper;
import com.huanxing.cloud.product.service.IGoodsSkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品sku
 *
 * @author lijx
 * @since 2022/2/26 16:37
 */
@Service
public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> implements IGoodsSkuService {

	@Override
	public List<GoodsSku> getListByIds(List<String> ids) {
		return baseMapper.selectListByIds(ids);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rollbackStockList(List<GoodsSkuStockReqDTO> goodsSkuStockRqDTOList) {
		goodsSkuStockRqDTOList.forEach(goodsSkuStockRqDTO -> {
			baseMapper.update(new GoodsSku(),
					Wrappers.<GoodsSku>lambdaUpdate()
						.eq(GoodsSku::getId, goodsSkuStockRqDTO.getSkuId())
						.setSql(" stock = stock + " + goodsSkuStockRqDTO.getStockNum()));
		});
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean reduceStock(List<GoodsSkuStockReqDTO> goodsSkuStockRqDTO) {
		for (GoodsSkuStockReqDTO goodsSkuStockReqDTO : goodsSkuStockRqDTO) {
			if (baseMapper.update(new GoodsSku(),
					Wrappers.<GoodsSku>lambdaUpdate()
						.eq(GoodsSku::getId, goodsSkuStockReqDTO.getSkuId())
						.ge(GoodsSku::getStock, 0)
						.setSql(" stock = stock - " + goodsSkuStockReqDTO.getStockNum())) > 0) {
				return Boolean.FALSE;
			}
		}
		return Boolean.TRUE;
	}

	@Override
	public List<GoodsSku> getSkuByIds(List<String> ids) {
		return baseMapper.selectSkuByIds(ids);
	}

}
